package util

import (
	"fmt"
	//"fmt"
	"os/exec"

	"github.com/xjasonlyu/tun2socks/v2/engine" // 引入 tun2socks 库
)

var key *engine.Key // tun2socks 库的关键结构体

var ch chan string = make(chan string)
var chstop chan string = make(chan string)

// "192.168.1.1:5215"
func TunStart(proxy_server string) {

	go func() {
		if key != nil {
			<-chstop
			TunStop()
		}

		ch <- proxy_server
	}()
	//return // 如果已经存在连接，则退出
	proxy := <-ch
	key = &engine.Key{
		MTU:                      0,
		Mark:                     0,
		Proxy:                    proxy, // 连接的代理服务器IP地址和端口号
		RestAPI:                  "",
		Device:                   "tun0",
		LogLevel:                 "info",
		Interface:                "",
		TCPModerateReceiveBuffer: false,
		TCPSendBufferSize:        "",
		TCPReceiveBufferSize:     "",
		UDPTimeout:               0,
	}
	engine.Insert(key)                                                                                                                  // 插入新的连接
	exec.Command("route", "add", "192.168.1.1", "mask", "255.255.255.255", "192.168.1.1", "metric", "5").Run()                          // 添加一个路由条目
	engine.Start()                                                                                                                      // 启动 tun2socks 服务
	exec.Command("netsh", "interface", "ip", "set", "address", "tun0", "static", "10.0.10.10", "255.255.255.0", "10.0.10.1", "3").Run() // 设置新的 IP 地址和子网掩码
	chstop <- "over"
}

func TunStop() {
	if key == nil {
		return
	}
	key = nil
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("wintun 恢复")
			key = nil
		}
	}()

	engine.Stop()
	// 停止 tun2socks 连接
	exec.Command("route", "delete", "0.0.0.0", "10.0.10.1").Run() // 删除路由表项
	// 删除与 tun2socks 连接有关的结构体

}
